var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

var Leaderships = require('../models/leadership');

var leaderRouter = express.Router();
leaderRouter.use(bodyParser.json());

leaderRouter.route('/')

.get(function(req, res, next) {
    console.log('Will send all the leaders to client!');
    Leaderships.find({}, function(err, leadership) {
        if (err) throw err;
        res.json(leadership);
    });
})

.post(function(req, res, next) {
    console.log('Will add the leader: ' + req.body.name + ' with details: ' + req.body.description);
    Leaderships.create(req.body, function(err, leadership) {
        if (err) throw err;
        console.log('Leadership created!');
        var id = leadership._id;

        res.writeHead(200, {
            'Content-Type': 'text/plain'
        });
        res.end('Added the leadership with id: ' + id);
    });
})


.delete(function(req, res, next) {
    console.log('Deleting all leaders');
    Leaderships.remove({}, function(err, resp) {
        if (err) throw err;
        res.json(resp);
    })
});

leaderRouter.route('/:leaderId')

.get(function(req, res, next) {
    console.log('Will send details of the leader: ' + req.params.leaderId + ' to you!');
    Leaderships.findById(req.params.leaderId, function(err, leadership) {
        if (err) throw err;
        res.json(leadership);
    });
})

.put(function(req, res, next) {
    Leaderships.findByIdAndUpdate(req.params.leaderId, {
        $set: req.body
    }, {
        new: true
    }, function(err, leadership) {
        if (err) throw err;
        res.json(leadership);
    });
})

.delete(function(req, res, next) {
    console.log('Deleting leader: ' + req.params.leaderId);
    Leaderships.findByIdAndRemove(req.params.leaderId, function(err, resp) {
        if (err) throw err;
        res.json(resp);
    });
});

module.exports = leaderRouter;